<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="110px"
      v-loading="formLoading"
    >
      <el-form-item label="班组编码" prop="teamCode">
        <el-input v-model="formData.teamCode" placeholder="请输入班组档案编码" />
      </el-form-item>
      <el-form-item label="班组名称" prop="teamName">
        <el-input v-model="formData.teamName" placeholder="请输入班组档案名称" />
      </el-form-item>
      <el-form-item label="班组长" prop="configOrgStaffArchivesId">
        <el-select 
          v-model="staffName" 
          filterable
          remote
          placeholder="请选择班组长"
          value-key="id"
          :remote-method="remoteStaffMethod"
          :loading="loading"
          @change="changeStaff"
        >
          <el-option
            v-for="(item) in staffNameList"
            :key="item['id']"
            :label="item['staffName']"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="configOrgDeptArchivesId">
        <el-select 
          v-model="deptName"
          filterable
          remote 
          placeholder="请选择所属部门"
          value-key="id"
          :remote-method="remoteDeptMethod"
          :loading="deptLoading"
          @change="changeDept"
        >
          <el-option
            v-for="item in deptNameList"
            :key="item['id']"
            :label="item['name']"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工资核算方式" prop="dictWageCheckWay">
        <el-select v-model="formData.dictWageCheckWay" placeholder="请选择性别">
          <el-option
            v-for="dict in getIntDictOptions('config_wage_check_way')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" />
      </el-form-item>
      <el-form-item label="班组状态" prop="dictEnableStatus">
        <el-select v-model="formData.dictEnableStatus" placeholder="请选择班组状态">
          <el-option
            v-for="dict in getIntDictOptions('dict_enable_status')"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions } from '@/utils/dict'
import * as ComponentApi from '@/api/componentApi/index'
import * as OrgTeamArchivesApi from '@/api/config/orgTeamArchives'

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  teamCode: undefined,
  teamName: undefined,
  configOrgStaffArchivesId: undefined,
  configOrgStaffArchivesName: undefined,
  configOrgDeptArchivesId: undefined,
  configOrgDeptArchivesName: undefined,
  dictWageCheckWay: undefined,  //工资核算方式
  remark: undefined,
  dictEnableStatus: undefined
})
const formRules = reactive({
  teamCode: [{ required: true, message: '班组档案编码不能为空', trigger: 'blur' }],
  teamName: [{ required: true, message: '班组档案名称不能为空', trigger: 'blur' }],
  configOrgDeptArchivesId: [{ required: true, message: '所属部门不能为空', trigger: 'change' }],
  dictWageCheckWay: [{ required: true, message: '工资核算方式不能为空', trigger: 'change' }],
  dictEnableStatus: [{ required: true, message: '班组状态不能为空', trigger: 'change' }]
})
const formRef = ref() // 表单 Ref
type OptionStaff = {
  id: number,
  staffName: string
}
type OptionDept = {
  id: number,
  name: string
}
const staffName = ref<OptionStaff>()
const deptName = ref<OptionDept>()
const staffNameList = ref<OptionStaff[]>([])
const deptNameList = ref<OptionStaff[]>([])
const loading = ref(false)  //班组长加载
const deptLoading = ref(false)  //部门加载

// 班组长改动
const changeStaff = (val) => {
  formData.value.configOrgStaffArchivesId = val.id
  formData.value.configOrgStaffArchivesName = val.staffName
}

// 部门改动
const changeDept = (val) => {
  console.log(val)
  formData.value.configOrgDeptArchivesId = val.id
  formData.value.configOrgDeptArchivesName = val.name
}

// 获取班组长
const remoteStaffMethod = async (query: string) => {
  if (query) {
    loading.value = true
    try {
      let res = await ComponentApi.getStaffList(query)
      console.log(res)
      staffNameList.value = res
    } finally {
      loading.value = false
    }
  } else {
    staffNameList.value = []
  }
}

// 获取部门
const remoteDeptMethod = async (query: string) => {
  if (query) {
    deptLoading.value = true
    try {
      let res = await ComponentApi.getDeptList(query)
      deptNameList.value = res
    } finally {
      deptLoading.value = false
    }
  } else {
    deptNameList.value = []
  }
}

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await OrgTeamArchivesApi.getOrgTeamArchives(id)
      staffNameList.value = [{
        id: formData.value.configOrgStaffArchivesId,
        staffName: formData.value.configOrgStaffArchivesName
      }]
      staffName.value = {
        id: formData.value.configOrgStaffArchivesId,
        staffName: formData.value.configOrgStaffArchivesName
      }
      deptNameList.value = [{
        id: formData.value.configOrgDeptArchivesId,
        name: formData.value.configOrgDeptArchivesName
      }]
      deptName.value = {
        id: formData.value.configOrgDeptArchivesId,
        name: formData.value.configOrgDeptArchivesName
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  console.log(formData.value)
  // 校验表单
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as OrgTeamArchivesApi.OrgTeamArchivesVO
    if (formType.value === 'create') {
      await OrgTeamArchivesApi.createOrgTeamArchives(data)
      message.success(t('common.createSuccess'))
    } else {
      await OrgTeamArchivesApi.updateOrgTeamArchives(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    teamCode: undefined,
    teamName: undefined,
    configOrgStaffArchivesId: undefined,
    configOrgStaffArchivesName: undefined,
    configOrgDeptArchivesId: undefined,
    configOrgDeptArchivesName: undefined,
    remark: undefined,
    dictEnableStatus: undefined
  }
  formRef.value?.resetFields()
}
</script>
